<!--
 * @Author: 小花
 * @Date: 2022-03-04 16:50:27
 * @LastEditors: 小花
 * @LastEditTime: 2022-05-14 20:52:32
 * @Description: 
-->
<template>
  <div class='repairRecord_container'>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>申请记录</span>
      </div>

      <el-table :data="tableDataPaging" border v-loading="tableDataLoading"
        element-loading-text="拼命加载中" :header-cell-style="{background:'#F3F4F7',color:'#555'}"
        :default-sort="{prop: 'repairDate', order: 'descending'}" @filter-change="filterTagTable"
        style="width: 100%">
        <el-table-column type="index" align="center" width="60" :index="tableIndex">
        </el-table-column>
        <el-table-column highlight-current-row align="center" prop="orderId" label="单号" width="180">
        </el-table-column>
        <el-table-column align="center" prop="repairAddress" label="报修地址" width="180">
        </el-table-column>
        <el-table-column align="center" prop="repairContent" label="报修问题" width="180">
        </el-table-column>
        <el-table-column align="center" prop="repairTypeEntity.typeValue" label="报修类型" width="180">
        </el-table-column>
        <el-table-column align="center" prop="repairStatusEntity.statusValue" label="报修状态"
          width="180" :filters="repairStatusFilters" filter-placement="bottom-end"
          column-key="aStatus">
          <template #default="scope">
            <el-tooltip v-if="scope.row.rejectReason != null"
              :content="`原因: ${scope.row.rejectReason}`" placement="top" effect="light"
              style="cursor: pointer;">
              <el-tag :type="repairStatusStyle(scope.row.statusCode)" effect="light"
                disable-transitions>
                {{scope.row.repairStatusEntity.statusValue}}
              </el-tag>
            </el-tooltip>
            <el-tag v-else :type="repairStatusStyle(scope.row.statusCode)" effect="light"
              disable-transitions>
              {{scope.row.repairStatusEntity.statusValue}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="repairPhone" label="联系号码" width="180">
        </el-table-column>
        <el-table-column align="center" prop="repairDate" label="报修时间" width="200" sortable>
        </el-table-column>
        <el-table-column align="center" prop="repairComplateDate" label="完成时间" width="180" sortable>
        </el-table-column>
        <el-table-column align="center" label="图片资料" width="180">
          <template #default="scope">
            <el-image style="width: 30px; height: 30px; margin: 5px;"
              v-for="url in scope.row.imgUrl" :key="url" :src="url" fit="fill"
              :preview-src-list="scope.row.imgUrl" slot="reference"></el-image>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="workerEntity.workerName" label="维修员" width="180">
        </el-table-column>
        <!-- v-if="store.waitPayOrders.length !== 0" -->
        <el-table-column align="center" fixed="right" label="操作" width="180"
          v-if="tableDataPaging.length !== 0">
          <template #default="scope">
            <div>
              <el-popconfirm title="你确定要取消报修吗？" v-if="scope.row.statusCode === 1"
                @confirm="cancelOrder(scope.row)">
                <template #reference>
                  <el-button type="primary">
                    <i class="fa fa-share"></i>取消
                  </el-button>
                </template>
              </el-popconfirm>
              <el-button
                :type="['danger','success'].at(handlerWaitChargeBtnShowText(scope.row.orderId))"
                v-else-if=" handlerWaitChargeBtnShow(scope.row.orderId)" plain
                @click="chargeOn(scope.row.orderId)">
                {{['待缴费订单','已缴费订单'].at(handlerWaitChargeBtnShowText(scope.row.orderId))}}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination @size-change="val=>pagination.pageSize = val"
          @current-change="val=>pagination.currentPage = val" :current-page="pagination.currentPage"
          :pager-count="pagination.pagerCount" :page-sizes="pagination.pageSizes"
          :page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total" background>
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { useMainStore } from '@/js/store.js'
import { imgUrlAddress, repairStatusStyle } from '@/js/public.js'
import jsmd5 from 'js-md5'

var that;
export default {
  data () {
    //这里存放数据
    return {
      store: useMainStore(),
      tableData: [],
      tableDataLoading: true,
      tableDataF: [],
      pagination: {
        pageSize: 10,
        pageSizes: [10, 50, 100, 200],
        pagerCount: 5,
        currentPage: 1,
        total: 0,
      },
      queryList: {
        aStatus: []
      },
      repairStatusStyle,
    }
  },
  //监听属性 类似于data概念
  computed: {
    tableDataPaging () {
      const { currentPage, pageSize } = this.pagination
      return this.tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
    },
    repairStatusFilters () {
      let filters = new Array();
      if (this.store.repairStatus === null) return []
      this.store.repairStatus.forEach((item, idx) => {
        let obj = {
          text: item.statusValue,
          value: item.statusValue
        }
        filters.push(obj);
      })
      return filters;
    }
  },
  //监控data中的数据变化
  watch: {
    tableData: function (val) {
      this.pagination.total = val.length;
    }
  },
  //方法集合
  methods: {
    handlerWaitChargeBtnShow (orderId) {
      let flag = this.store.waitPayOrders.find(v => v.orderId == orderId);
      return flag ? true : false;
    },
    handlerWaitChargeBtnShowText (orderId) {
      return this.store.waitPayOrders.some(v => {
        if (v.orderId == orderId) return v.chargeStatus;
      })
    },
    /**
     * @description: 获取hashCode，本地存在则直接进入
     * @param {*} orderId
     * @return {*}
     * @author: 小花
     */
    chargeOn (orderId) {
      let applyIds = new Array();
      let order = new Array()
      for (const iterator of this.store.waitPayOrders) {
        if (iterator.orderId == orderId) {
          applyIds.push(iterator.applyId);
          order.push(iterator);
        }
      }

      if (localStorage.getItem(orderId) == null && !this.handlerWaitChargeBtnShowText(orderId)) {
        let time = new Date().getTime();
        let md5ApplyId = jsmd5(JSON.stringify(applyIds) + '/userHome/getPayHashCode' + time);

        this.axios.post("/userHome/getPayHashCode", { applyIds: JSON.stringify(applyIds), md5ApplyId, time }).then(res => {
          if (res.data.code != 43000) {
            this.$message.error(res.data.msg);
            return;
          }
          localStorage.setItem(orderId, res.data.data);
          localStorage.removeItem(`payInfo-${orderId}`)
        })
      }

      this.$router.push({
        name: 'charge_on',
        query: {
          orderId,
        }
      })
    },
    /**
     * @description: 取消报修单
     * @param {*}
     * @return {*}
     * @author: 小花
     */
    cancelOrder (row) {
      let data = JSON.parse(JSON.stringify(row));
      data.imgUrl = JSON.stringify(data.imgUrl);
      this.axios.post("/userHome/cancelOrder", data).then(res => {
        if (res.data.code == 43000) {
          this.tableData.some((value, index) => {
            if (value.orderId == data.orderId) {
              this.tableData.splice(index, 1);
              return true;
            }
          })
          this.$message.success(res.data.msg);
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    tableIndex (index) {
      return (index + 1) + (this.pagination.currentPage - 1) * this.pagination.pageSize;
    },
    filterTagTable (filters) {
      this.queryList.aStatus = filters.aStatus;
      if (filters.aStatus) {
        this.tableDataF = this.tableData.filter((element, index, array) => {
          if (filters.aStatus.indexOf(element.repairStatusEntity.statusValue) != -1) return true;
          return false;
        })
      }
    },
    queryUserOrderRecord () {
      this.axios.get("/userHome/queryUserOrderRecord").then(res => {
        let { orderFormEntityList, applyMaterialEntityList } = { ...res.data.data };

        this.tableData = orderFormEntityList ? orderFormEntityList.reverse() : [];
        this.store.waitPayOrders = applyMaterialEntityList || [];

        this.tableData.forEach((item, idx) => {
          this.tableData[idx].imgUrl = imgUrlAddress(item.imgUrl);
        })
        this.tableDataLoading = false;
      })
    },
    getRepairStatus () {
      if (this.store.repairStatus !== null) return;
      this.axios.get("/userHome/repairStatus").then(res => {
        this.store.repairStatus = res.data.data;
      })
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created () {
    this.queryUserOrderRecord();
    this.getRepairStatus();
    that = this;
  }
}
</script>

<style lang="scss" scoped>
//@import url(); 引入公共css类
.repairRecord_container {
  .pagination {
    display: flex;
    justify-content: center;
    margin-top: 1rem;
    align-items: center;
    .infoTip {
      color: gray;
      font-size: 12px;
      padding: 5px;
    }
  }
}
</style>
